// const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
// var request = require("../request/request.js");
const config = require('../../../utils/request/config.js').default

const base64 = require("./base64.js"); //Base64,hmac,sha1,crypto相关算法
require("./hmac.js");
require("./sha1.js");
const Crypto = require("./crypto.js");

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
const env = {
	AccessKeySecret: "", // AccessKeySecret 去你的阿里云上控制台上找
	OSSAccessKeyId: "", // AccessKeyId 去你的阿里云上控制台上找
	timeout: 87600, //这个是上传文件时Policy的失效时间
}; //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;

const aliyunServerURL = config.baseUploadUrl

const uploadFile = async function(filePath, successc, failc, dir = 'framework/') {
	if (!filePath || filePath.length < 9) {
		uni.showToast({
			title: "图片错误，请重试",
			icon: 'none'
		});
		return;
	}
	uni.showLoading({
		title:'上传中'
	})
	uni.request({
		url: config.baseUrl + '/aliyun/oss/token',
		method: 'GET',
		success: (result) => {
			if(result.data.code == 200){
				let data = result.data.data
				console.log(data)
				//图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
				const aliyunFileKey =
					dir + new Date().getTime() + Math.floor(Math.random() * 150) + ".png";
				
				const policyBase64 = getPolicyBase64();
				const signature = getSignature(policyBase64, data.accessKeySecret); //获取签名
				uni.uploadFile({
					url: aliyunServerURL, //开发者服务器 url
					filePath: filePath, //要上传文件资源的路径
					name: "file", //必须填file
					formData: {
						key: aliyunFileKey,
						policy: policyBase64,
						OSSAccessKeyId: data.accessKeyId,
						signature: signature,
						success_action_status: "200",
					},
					success: function(res) {
						uni.hideLoading()
						// console.log('res',res);
						// console.log(res);
						if (res.statusCode != 200) {
							failc(new Error("上传错误:" + JSON.stringify(res)));
							return;
						}
						// console.log(aliyunServerURL + aliyunFileKey);
						successc(aliyunServerURL + aliyunFileKey);
					},
					fail: function(err) {
						uni.hideLoading()
						err.wxaddinfo = aliyunServerURL;
						failc(err);
					},
				});
			}
		}
	})
	
};

const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		expiration: srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		conditions: [
			["content-length-range", 0, 5 * 1024 * 1024], // 设置上传文件的大小限制,5mb
		],
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	return policyBase64;
};

const getSignature = function(policyBase64,accessKeySecret) {
	const accesskey = accessKeySecret;

	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true,
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
};

module.exports = uploadFile;